import { defineStore } from 'pinia'
import { ref, onMounted } from 'vue'
import { useCourseStore } from './course'

export const useClassScheduleStore = defineStore('classSchedule', () => {
    const courseStore = useCourseStore()
    const classSchedules = ref([
        {
            id: 1,
            courseId: 1,
            courseName: '',
            teacherName: '张老师',
            classDate: '2024-08-08',
            classTime: '10:00',
        },
        {
            id: 2,
            courseId: 2,
            courseName: '',
            teacherName: '张老师',
            classDate: '2024-08-09',
            classTime: '10:00',
        }
    ])

    const getClassScheduleById = (id) => {
        return classSchedules.value.find(item => item.id === id)
    }

    const setInfoToSchedule = () =>{
        classSchedules.value.forEach(schedule => {
            const course = courseStore.getCourseById(schedule.courseId)
            schedule.courseName = course.courseName
        })
    }

    const addSchedule = (schedule) => {
        const course = courseStore.getCourseById(schedule.courseId)
        classSchedules.value.push({
            ...schedule, 
            id: classSchedules.value.length + 1, 
            courseName: course.courseName,
            classDate: getFormattedDate(schedule.classDate),
        })
    }

    const copySchedule = (fromDate, toDate) => {
        fromDate = getFormattedDate(fromDate)
        toDate = getFormattedDate(toDate)
        const rawShedules = classSchedules.value.filter((schedule) => schedule.classDate === fromDate)
        rawShedules.forEach((schedule) => {
            classSchedules.value.push({
                ...schedule, 
                id: classSchedules.value.length + 1, 
                classDate: toDate
            })
        })
    }

    const getFormattedDate = (date) => {
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    }

    const deleteClassSchedule = (id) => {
        const index = classSchedules.value.findIndex(schedule => schedule.id === id)
        classSchedules.value.splice(index, 1)
    }

    onMounted(() => {
        setInfoToSchedule()
    })

    return {
        classSchedules,
        getClassScheduleById,
        addSchedule,
        copySchedule,
        deleteClassSchedule
    }
})
